import os
import json
import time
import requests
from pprint import pprint

CONF_PATH=os.path.join(os.path.dirname(__file__),'conf')
IMG_PATH=os.path.join(os.path.dirname(__file__),'imgs')
Cache_Path=os.path.join(CONF_PATH,'wxpy.pkl')

APPID = 'gAN9RwevbV1fbx4'
TOKEN = 'uEj3814l9YPZFQiNRpu0kymIANqxsu'
EncodingAESKey = 'ue2gZyLMsOK53D5U5VKUL67v4x7zHMekMGbqWSoOBG'
cgai_url = 'https://openai.weixin.qq.com/openapi/aibot/{}'.format(TOKEN)
signature='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJjZ2FpMjAyMCIsImlhdCI6MTU4ODY0MzUxMywiZXhwIjoxNTg4NjUwNzEzfQ.5Cr6rc9s8Pwp-1riXpVe9_XTHtIJC4Ub1VmtElCcsjE'

def get_signature(save_path,token):#save_path,
    """
    微信的signature是2个小时
    :param save_path:
    :param token:
    :return:
    """
    user_name='老张'
    userid='cgai2020'
    url='https://openai.weixin.qq.com/openapi/sign/{}'.format(token)
    data={'user_name':user_name,'userid':userid}
    head = {"Content-Type": "application/json"}
    respons = requests.post(url, json.dumps(data), headers=head)
    signature=''
    if respons:
        signature=respons.json()['signature']
        with open(save_path,'w',encoding='utf8') as w:
            w.write(signature)
    return signature


def postStart(signature,query, token):
    url='https://openai.weixin.qq.com/openapi/aibot/{}'.format(token)
    data = {}
    data['signature'] = signature
    data['query'] = query
    head = {"Content-Type": "application/json"}
    # content = self.request(self.url, "POST", data, head)
    content = requests.post(url, json.dumps(data), headers=head)
    answer=''
    if content:
        answer=content.json()#['answer']
    return answer


Baidu_AppID='11076578'
Baidu_AppKey='kkZ0S17bqzxTkuQucBpWUsBv'
Baidu_SK='OBClRtM6VfyvfKpoKqyfgRIFVj2Wsbs4'

def get_baidu_AT(save_path,Baidu_AppKey,Baidu_SK):
    """
    百度的access_token是30天权限
    :param save_path:
    :param Baidu_AppKey:
    :param Baidu_SK:
    :return:
    """
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(Baidu_AppKey,Baidu_SK)
    response = requests.get(host)

    access_token=''
    if response:
        access_token=response.json()['access_token']
        with open(save_path,'w',encoding='utf8') as w:
            w.write(access_token)
    return access_token




# signature_path=os.path.join(CONF_PATH,'signature')
# sign=get_signature(signature_path,TOKEN)
# print(sign)

# query='我想听伍佰的歌曲'
# answer=postStart(signature,query,TOKEN)
# pprint(answer)

baidu_at_path=os.path.join(CONF_PATH,'baidu_at')
baidu_at=get_baidu_AT(baidu_at_path,Baidu_AppKey,Baidu_SK)
print(baidu_at)

# while True:
#     signature_path = os.path.join(CONF_PATH, 'signature')
#     sign=get_signature(signature_path,TOKEN)
#     time.sleep(7000)